package com.lingshang.service.impl;

import com.lingshang.bean.*;
import com.lingshang.dao.BookDao;
import com.lingshang.dao.OrderDao;
import com.lingshang.dao.OrderItemDao;
import com.lingshang.dao.impl.BookDaoImpl;
import com.lingshang.dao.impl.OrderDaoImpl;
import com.lingshang.dao.impl.OrderItemDaoImpl;
import com.lingshang.service.OrderService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Date:2020/10/28
 * Author:Ling
 * Description:
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao=new OrderDaoImpl();
    private OrderItemDao orderItemDao=new OrderItemDaoImpl();
    private BookDao bookDao=new BookDaoImpl();

    @Override
    public String checkout(Cart cart, User user) {
        //将当前时间戳
        String orderId = System.currentTimeMillis() + "";
        //获取系统当前时间
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置时间格式
        String createTime = sdf.format(date);

        //创建订单对象
        Order order=new Order(orderId,createTime,cart.getTotalCount(),cart.getTotalAmount(),0,user.getId());

        //保存订单
        orderDao.saveOrder(order);

        //获取购物车的购物项
        List<CartItem> cartItemList = cart.getCartItemList();
        //将购物项进行循环，把其中每一个购物项转换为每一个订单项
        for (CartItem cartItem : cartItemList) {
            //将购物项转换为订单项
            Book book = cartItem.getBook();
            OrderItem orderItem=new OrderItem(null,createTime,book.getTitle(),book.getAuthor(),book.getPrice(),book.getImgPath(),cartItem.getCount(),cartItem.getAmount(),orderId);

            //保存订单项
            orderItemDao.saveOrderItem(orderItem);
            //更新图书的库存和销量
            bookDao.updateSalesAndStock(book.getId(),cartItem.getCount());
        }

        return orderId;
    }

    @Override
    public List<Order> getMyOrder(Integer userId) {
        return orderDao.getMyOrder(userId);
    }

    @Override
    public List<OrderItem> getOrderDetails(String orderId) {
        return orderItemDao.getOrderDetails(orderId);
    }

    @Override
    public void takeOrder(String orderId) {
        orderDao.updateStatus(orderId,2);
    }

    @Override
    public List<Order> getAllOrder() {
        return orderDao.getAllOrder();
    }

    @Override
    public void sendOrder(String orderId) {
        orderDao.updateStatus(orderId,1);
    }
}
